package com.buding.fx.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.buding.fx.common.constant.CssStyleInfo;
import com.buding.fx.common.enums.PosEnum;
import com.buding.fx.entity.Menu;
import com.buding.fx.entity.SystemConfigInfo;
import com.buding.fx.service.BaseViewService;
import com.buding.fx.utils.NotifyThread;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.TextFieldTreeCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.paint.Color;
import javafx.util.Callback;
import javafx.util.StringConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mingdongwei-jwk
 * @date 2022/09/15 10:59
 * @class com.buding.fx.service
 * @Description
 */

public class LeftPinaBuildService implements BaseViewService {
    private Logger logger = LoggerFactory.getLogger(LeftPinaBuildService.class);

    @Override
    public Node show(SystemConfigInfo config) {
        /**
         * 默认初始化，需要构造一个默认的点击的node，如果没有暂时为null
         */
        return onclickShow(null,config);
    }

    @Override
    public Node onclickShow(Node onClickNode, SystemConfigInfo configInfo) {
        CssStyleInfo css = configInfo.getCss();
        Border border = new Border(new BorderStroke(Color.web(css.getLeft_node_right_border_color()), BorderStrokeStyle.SOLID,null,new BorderWidths(0,2,0,0)));
        TreeView<Menu> treeView = new TreeView<>();
        treeView.setBorder(border);
        treeView.setPrefHeight(css.getLeft_height());
        treeView.setPrefWidth(css.getLeft_wight());
        treeView.setFixedCellSize(30);  //上下间隔
        treeView.setShowRoot(false);  //不显示根节点
        //treeView.getFocusModel().focus(1);//默认选择的节点
        //treeView.getExpandedItemCount();  获取展开的节点
        treeView.setStyle("-fx-font-size: 14;");
        logger.info("left node width: "+treeView.getPrefWidth()+"; left node height: "+treeView.getPrefHeight());
         if (onClickNode!=null){
            Long meunuId = (Long) onClickNode.getProperties().get("menuId");
            logger.info("click top menu id: "+meunuId);
            //首先根据menuId，获取所有的一级节点，然后遍历所有的一级节点下面
            List<Menu> menus = configInfo.getMenus();
            Map<Long, List<Menu>> parentMenus = menus.stream().filter(item -> item.getPid() != null).collect(Collectors.groupingBy(Menu::getPid));
            TreeItem<Menu> rootItem = rebuildTreeInfo(meunuId,menus,parentMenus,new TreeItem<>());
            if (rootItem!=null){
                treeView.setRoot(rootItem);
            }
        }

        treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<Menu>>() {
            @Override
            public void changed(ObservableValue<? extends TreeItem<Menu>> observable, TreeItem<Menu> oldValue, TreeItem<Menu> newValue) {
                Menu menu = newValue.getValue();
                logger.info("select menu: "+menu);
                //如果有跳转地址，说明中心部分需要展示
                if (menu.getRedirectUrl()!=null){
                    CenterBuildService centerBuildService = new CenterBuildService();
                    Platform.runLater(new NotifyThread(configInfo.getBorderPane(),  centerBuildService.selectShow(menu,configInfo), PosEnum.CENTER));
                }
            }
        });

        treeView.setCellFactory(new Callback<TreeView<Menu>, TreeCell<Menu>>() {
            @Override
            public TreeCell<Menu> call(TreeView<Menu> param) {
                TreeCell<Menu> treeCell = new TreeCell<Menu>(){
                    @Override
                    protected void updateItem(Menu item, boolean empty) {
                        super.updateItem(item, empty);
                        if (!empty){
                            logger.info("menu format ite: "+item);
                        }
                    }
                };
                return treeCell;
            }
        });
        treeView.setCellFactory(TextFieldTreeCell.forTreeView(new StringConverter<Menu>() {
            @Override
            public String toString(Menu object) {
                if (object!=null){
                    return object.getTitle();
                }
               return "";
            }

            @Override
            public Menu fromString(String string) {
                return new Menu();
            }
        }));

        return treeView;
    }

    /**
     *
     * @param menuId
     * @param list
     * @param map
     * @param root
     * @return
     */
    public static TreeItem<Menu> rebuildTreeInfo(Long menuId,List<Menu> list, Map<Long, List<Menu>> map,TreeItem<Menu> root) {
       if (menuId!=null && CollectionUtil.isNotEmpty(list) && CollectionUtil.isNotEmpty(map)){
            List<Menu> chidrens = map.get(menuId);
            if (CollectionUtil.isNotEmpty(chidrens)){
                for (Menu rootItem : chidrens){
                    TreeItem<Menu> item = new TreeItem<>(rootItem);
                    String iconUrl = rootItem.getIconPath()+rootItem.getIcon();
                    Image image = new Image(iconUrl);
                    ImageView imgView = new ImageView(image);
                    imgView.setFitHeight(16);
                    imgView.setFitWidth(16);
                    item.setGraphic(imgView);
                    item.setExpanded(true);
                    root.getChildren().add(item);
                    rebuildTreeInfo(rootItem.getId(),chidrens,map,item);
                }
            }
       }
       return root;
    }

}
